#include "bsp_config.h"

/* Variable holding number of times ESP32 restarted since first boot.
 * It is placed into RTC memory using RTC_DATA_ATTR and
 * maintains its value when ESP32 wakes from deep sleep.
 */
// RTC_DATA_ATTR static int boot_count = 0; //存放于RTC_Memory中

//time_mark:1 表示正在获取时间   time_mark:0 表示已经完成获取时间
uint8_t time_mark = 0; //用来标记当前正在进行获取时间

/**
 *  @brief 设置当前时间函数
 *  @param struct timeval *tv 指向存有当前需要设置的时间的变量
 *         单位是秒,
 *  @brief 无  
 */
void sntp_sync_time(struct timeval *tv)
{
    xSemaphoreTake(time_mutex, portMAX_DELAY);
    sntp_restart();
    settimeofday(tv, NULL);
    ESP_LOGI(TAG, "Time is synchronized from custom code");
    sntp_set_sync_status(SNTP_SYNC_STATUS_COMPLETED);
    xSemaphoreGive(time_mutex);
}

void time_sync_notification_cb(struct timeval *tv)
{
    ESP_LOGI(TAG, "Notification of a time synchronization event");
}

static void initialize_sntp(void)
{
    ESP_LOGI(TAG, "Initializing SNTP");
    sntp_setoperatingmode(SNTP_OPMODE_POLL);
    sntp_setservername(0, "pool.ntp.org");
    sntp_set_time_sync_notification_cb(time_sync_notification_cb);
    sntp_init();
}

static void obtain_time(void)
{ //每次wifi连接上后,都会执行
    initialize_sntp();

    // wait for time to be set
    time_t now = 0;
    struct tm timeinfo = {0};
    int retry = 0;
    const int retry_count = 10;
    while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET && ++retry < retry_count)
    {
        ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
        vTaskDelay(2000 / portTICK_PERIOD_MS);
    }
    time(&now);
    localtime_r(&now, &timeinfo);
}

volatile struct tm current_time;

void get_time(uint8_t mark)
{
    // ++boot_count;
    // ESP_LOGI(TAG, "Boot count: %d", boot_count);
    time_t now;
    struct tm timeinfo;

		xSemaphoreTake(time_mutex, portMAX_DELAY);
        time(&now);
        localtime_r(&now, &timeinfo);
        // Is time set? If not, tm_year will be (1970 - 1900).
        // if (timeinfo.tm_year < (2016 - 1900))
        // {
        //     ESP_LOGI(TAG, "Time is not set yet. Connecting to WiFi and getting time over NTP.");
        //     obtain_time();
        //     // update 'now' variable with current time
        //     time(&now);
        // }
        if (mark)
        { //第一次执行该函数时从网络获取一次时间
            obtain_time();
            // update 'now' variable with current time
            time(&now);
        }

        char strftime_buf[64];

        // // Set timezone to Eastern Standard Time and print local time
        // setenv("TZ", "EST5EDT,M3.2.0/2,M11.1.0", 1);
        // tzset();
        // localtime_r(&now, &timeinfo);
        // strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
        // ESP_LOGI(TAG, "The current date/time in New York is: %s", strftime_buf);

        // Set timezone to China Standard Time
        setenv("TZ", "CST-8", 1);
        tzset();
        localtime_r(&now, &timeinfo);
        strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
        ESP_LOGI(TAG, "The current date/time in Shanghai is: %s,_%d", strftime_buf,now);
        current_time = timeinfo;

		xSemaphoreGive(time_mutex);
}